<template>
  <el-dialog title="分配角色" :visible="show" @open="handleOpen" @close="handleClose">
    <el-form :model="formMessage" ref="form">
      <el-form-item label="角色">
        <el-select v-model="formMessage.roleIdList" multiple>
          <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleConfirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
import { getAllRoles, getUserRole, setUserRole } from '@/services/boss'
import { Form, Message } from 'element-ui'
import { Vue, Component, Prop, Emit } from 'vue-property-decorator'

@Component
export default class SetRole extends Vue {
  @Prop({ type: Boolean, default: false }) show = false;
  @Prop({ type: Number }) userId = NaN;

  private formMessage: any = {
    roleIdList: []
  }

  private roleList: Array<any> = []
  private loading = false

  async handleOpen () {
    let response = await getAllRoles()
    this.roleList = response.data || []
    response = await getUserRole(this.userId)
    this.formMessage.roleIdList = response.data.map((item: any) => item.id)
  }

  @Emit('success')
  handleSuccess () {
    this.handleClose()
  }

  @Emit('close')
  handleClose () {
    (this.$refs.form as Form).resetFields()
  }

  async handleConfirm () {
    try {
      this.loading = true
      const params = {
        id: this.userId,
        roleIdList: this.formMessage.roleIdList
      }
      await setUserRole(params)
      Message.success('分配成功')
      this.handleSuccess()
    } catch (e: any) {
      console.error(e)
      Message.error(e.message)
    } finally {
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
